package com.hospital.workstation.utils;

import com.deepoove.poi.XWPFTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @ClassName PoiTlUtils
 * @description:
 * @author: whb
 * @create: 2023-02-21 15:57
 * @Version 1.0
 **/
@Slf4j
public class PoiTlUtils {
    private static Logger logger = LoggerFactory.getLogger(PoiTlUtils.class);

    /**
     * 渲染Word 文件
     *
     * @param templatePath 文件模板路径
     * @param fileDir      生成文件的路径
     * @param fileName     生成的文件名
     * @param paramMap     数据
     * @return
     */
    public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) {
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir + "/" + fileName;
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
        }
        return filePath;
    }

    /**
     * 写入响应流
     *
     * @param response
     * @param template
     */
    public static void createOutPusStream(HttpServletResponse response, XWPFTemplate template, String fileName) {
        OutputStream out = null;
        try {
            //=================生成word到设置浏览默认下载地址=================
            response.setCharacterEncoding("UTF-8");
            // 设置文件名
            response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".docx;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8") + ".docx");
            //设置文件格式
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Type", "application/vnd.ms-word");
            response.addHeader("Content-Type", "application/x-msword");
            out = response.getOutputStream();
            template.write(out);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (template != null) {
                try {
                    template.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
